package kr.hkit.powerjava.chapter24.work3.dao;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import kr.hkit.powerjava.chapter24.work3.vo.Department;

public class DepartmentDao implements InterfaceDao<Department> {
	private ArrayList<Department> list;
	private final String filePath = "departmentlist.data";
	
	@Override
	public void insertItem(Department Item) {
		if (!list.contains(Item)){
			list.add(Item);
		}
	}
	
	@Override
	public void deleteItem(Department Item) {
		if (list.contains(Item)){
			list.remove(Item);
		}
	}
	
	@Override
	public void updateItem(Department Item) {
		if (list.contains(Item)){
			list.set(list.indexOf(Item), Item);
		}
	}
	
	@Override
	public Department searchItem(Department Item) {
		Department searchValue = null;
		if (list.contains(Item))
			searchValue = list.get(list.indexOf(Item));
		return searchValue;
	}
	
	@Override
	public void prnItemList(Comparator<Department> comp) {
		if (comp == null){
			Collections.sort(list);
		} else {
			Collections.sort(list, comp);
		}
		for (Department std : list)
			System.out.println(std);
	}
	
	@Override
	public void loadFile() {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filePath)));
			list = (ArrayList<Department>) ois.readObject();
		} catch (FileNotFoundException e) {
			try {
				new File(filePath).createNewFile();
				list = new ArrayList<>();
			} catch (IOException e1) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null) try { ois.close(); } catch(Exception e1){}
		}
	}
	
	@Override
	public void saveFile() {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filePath)));
			oos.writeObject(list);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (oos != null) try { oos.close(); } catch(Exception e){}
		}
	}
	
}
